package ar.edu.isft189.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ar.edu.isft189.dao.MesaExamenCrudDao;
import ar.edu.isft189.model.AlumnoExamen;
import ar.edu.isft189.model.MesaExamen;
import ar.edu.isft189.model.Usuario;
import ar.edu.isft189.pdfBox.service.PdfBoxServiceMesaExamen;
import ar.edu.isft189.utility.Resultado;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;

public class CRUDMesaExamen extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private MesaExamenCrudDao dao;
	private List<MesaExamen> lstMesas;
	private Gson gson;
	private Usuario u;

	public CRUDMesaExamen() {
		dao = new MesaExamenCrudDao();
		new Resultado();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		if (request.getParameter("action") != null) {			
			
			
			u = (Usuario) request.getSession().getAttribute("usuario");
			String action = (String) request.getParameter("action");
			response.setContentType("application/json");			

			switch (action) {
			case "listMesasExamen":
				listMesasExamen(request, response);	
				break;				
			case "crearMesaExamen":
				crearMesasExamen(request, response);
				break;				
			case "updateMesaExamen":
				updateMesasExamen(request, response);
				break;				
			case "updateNotaAlumno":
				updateNotaAlumno(request, response);
				break;				
			case "cerrarMesaExamen":
				cerrarMesaExamen(request, response);
				break;
			case "abrirMesaExamen":
				abrirMesaExamen(request, response);
				break;				
			case "listAlumnosPorMesa":
					listAlumnosPorMesa(request, response);
				break;
			case "exportarActaVolante":
				exportarActaVolante(request, response);
				break;					
//			case "exportarActaDefinitiva":
//				exportarActaDefinitiva(request, response);
//				break;
			}	
		}
	}
	
	
	/**	METODOS */
	

	/**
	 * Lista todas las mesas de examenes o las de un docente determinado
	 * 
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	private void listMesasExamen(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		
		gson = new Gson();
		lstMesas = new ArrayList<MesaExamen>();	
		try {			
			
			String lt = null;
			
			if(u.getPerfil() == 2)
				lt = Long.toString(u.getLegajo());
			
			// Obtengo la lista de Mesas
			lstMesas = dao.getAllMesas(lt);
			// Convert Java Object to Json
			JsonElement element = gson.toJsonTree(lstMesas,
					new TypeToken<List<MesaExamen>>() {
					}.getType());
			JsonArray jsonArray = element.getAsJsonArray();
			String listData = jsonArray.toString();
			// Return Json in the format required by jTable plugin
			listData = "{\"Result\":\"OK\",\"Records\":" + listData
					+ " ,\"TotalRecordCount\":" + lstMesas.size() + "}";
			System.out.println("Json " + listData);
			response.getWriter().print(listData);

		} catch (Exception ex) {
			String error = "{\"Result\":\"ERROR\",\"Message\":"
					+ ex.getMessage() + "}";
			response.getWriter().print(error);
			System.out.println("Json " + error);
			ex.printStackTrace();
		}		
	}	
	
	/**
	 * Da de alta una mesa de examen nueva
	 * 
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	private void crearMesasExamen(HttpServletRequest request,
			HttpServletResponse response) throws IOException{			
		
		MesaExamen me = new MesaExamen();
		lstMesas = new ArrayList<MesaExamen>();
		gson = new Gson();
		try {

			String fecha = request.getParameter("fecha").toString();
			int codigoM = Integer.parseInt(request.getParameter(
					"codigoM").toString());
			Integer folio = Integer.parseInt(request.getParameter(
					"folio").toString()) != 0 ? Integer
					.parseInt(request.getParameter("folio").toString())
					: 1;
			Integer libro = Integer.parseInt(request.getParameter(
					"libro").toString()) != 0 ? Integer
					.parseInt(request.getParameter("libro").toString())
					: 1;
			int titular = Integer.parseInt(request.getParameter(
					"titular").toString());
			int vocal1 = Integer.parseInt(request
					.getParameter("vocal1").toString());
			int vocal2 = Integer.parseInt(request
					.getParameter("vocal2").toString());
			int total = request.getParameter("cantExam") != null ? Integer
					.parseInt(request.getParameter("cantExam")
							.toString()) : 0;
			int aprob = request.getParameter("cantApr") != null ? Integer
					.parseInt(request.getParameter("cantApr")
							.toString()) : 0;
			int aus = request.getParameter("cantAus") != null ? Integer
					.parseInt(request.getParameter("cantAus")
							.toString()) : 0;

			me.setEstado("A");
			me.setFecha(fecha);
			me.setCodigoM(codigoM);
			me.setLibro(libro);
			me.setFolio(folio);
			me.setTitular(titular);
			me.setVocal1(vocal1);
			me.setVocal2(vocal2);
			me.setCantExam(total);
			me.setCantAus(aus);
			me.setCantAprob(aprob);

			me = dao.crearMesaExamen(me);
			lstMesas.add(me);
			// Convert Java Object to Json
			String json = gson.toJson(me);

			String data = "{\"Result\":\"OK\" ,\"Record\":" + json
					+ "}";
			response.getWriter().print(data);
		} catch (Exception ex) {
			String error = "{\"Result\":\"ERROR\",\"Message\":"
					+ ex.getStackTrace().toString() + "}";
			response.getWriter().print(error);
		}
	}
	
	/**
	 * Actualiza los datos de una meesa de examen
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void updateMesasExamen(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		
		MesaExamen me = new MesaExamen();

		int idm = request.getParameter("idm") != null ? Integer
				.parseInt(request.getParameter("idm")) : 0;

		String st = request.getParameter("estado") != null ? request
				.getParameter("estado").toString() : "A";

		Integer folio = Integer.parseInt(request.getParameter("folio")
				.toString()) != 0 ? Integer.parseInt(request
				.getParameter("folio").toString()) : 1;
		Integer libro = Integer.parseInt(request.getParameter("libro")
				.toString()) != 0 ? Integer.parseInt(request
				.getParameter("libro").toString()) : 1;
		int total = request.getParameter("cantExam") != null ? Integer
				.parseInt(request.getParameter("cantExam").toString())
				: 0;
		int aprob = request.getParameter("cantApr") != null ? Integer
				.parseInt(request.getParameter("cantApr").toString())
				: 0;
		int aus = request.getParameter("cantAus") != null ? Integer
				.parseInt(request.getParameter("cantAus").toString())
				: 0;

		me.setIdm(idm);
		me.setEstado(st);
		me.setLibro(libro);
		me.setFolio(folio);
		me.setCantExam(total);
		me.setCantAus(aus);
		me.setCantAprob(aprob);

		try {
			dao.updateMesaExamen(me);
			String data = "{\"Result\":\"OK\"}";
			response.getWriter().print(data);
		} catch (Exception ex) {
			String error = "{\"Result\":\"ERROR\",\"Message\":"
					+ ex.getStackTrace().toString() + "}";
			response.getWriter().print(error);
		}
		
	}
	
	/**
	 * Lista los alumnos de una mesa determinada
	 * 
	 * @param request
	 * @param response
	 * @throws IOException 
	 */	
	private void listAlumnosPorMesa(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		
		gson = new Gson();
		
		try {
			int mesaId = Integer.parseInt(request.getParameter("idm")
					.toString());

			List<AlumnoExamen> lstAl = dao.getStudentsByIdm(mesaId);

			// Convert Java Object to Json
			JsonElement element = gson.toJsonTree(lstAl,
					new TypeToken<List<AlumnoExamen>>() {
					}.getType());
			JsonArray jsonArray = element.getAsJsonArray();
			String listData = jsonArray.toString();
			// Return Json in the format required by jTable plugin
			listData = "{\"Result\":\"OK\",\"Records\":" + listData
					+ " ,\"TotalRecordCount\":" + lstAl.size() + "}";
			System.out.println("Json " + listData);
			response.getWriter().print(listData);

		} catch (Exception ex) {
			String error = "{\"Result\":\"ERROR\",\"Message\":"
					+ ex.getMessage() + "}";
			response.getWriter().print(error);
			System.out.println("Json " + error);
			ex.printStackTrace();
		}		
	}
	
	/**
	 * Actualiza la nota de un alumno
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void updateNotaAlumno(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		
		try {

			int mesaId = Integer.parseInt(request.getParameter("idm")
					.toString());
			int legajo = Integer.parseInt(request.getParameter(
					"legajoA").toString());
			int nota = Integer.parseInt(request.getParameter("nota")
					.toString());
			int codigoMe = Integer.parseInt(request.getParameter(
					"codigoMe").toString());

			AlumnoExamen ae = new AlumnoExamen();
			ae.setIdm(mesaId);
			ae.setLegajoA(legajo);
			ae.setNota(nota);
			ae.setCodigoMe(codigoMe);

			dao.updateNotaAlumno(ae);

			String data = "{\"Result\":\"OK\"}";
			response.getWriter().print(data);
		} catch (Exception ex) {
			String error = "{\"Result\":\"ERROR\",\"Message\":"
					+ ex.getMessage() + "}";
			response.getWriter().print(error);
			System.out.println("Json " + error);
			ex.printStackTrace();
		}		
	}
	
	/**
	 * Metodo que da por cerrada una mesa
	 * 
	 * @param request
	 * @param response
	 * @throws IOException 
	 */	
	private void cerrarMesaExamen(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		try {
			int mesaId = Integer.parseInt(request.getParameter("idm")
					.toString());

			dao.cerrarMesaExamen(mesaId);
			String data = "{\"Result\":\"OK\"}";
			response.getWriter().print(data);
		} catch (Exception ex) {
			String error = "{\"Result\":\"ERROR\",\"Message\":"
					+ ex.getMessage() + "}";
			response.getWriter().print(error);
			System.out.println("Json Result " + error);
			ex.printStackTrace();
		}		
	}
	
	
	/**
	 * Metodo que abre una mesade examenen que esta en estado P
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void abrirMesaExamen(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		try {
			int mesaId = Integer.parseInt(request.getParameter("idm")
					.toString());

			dao.abrirMesaExamen(mesaId);
			String data = "{\"Result\":\"OK\"}";
			response.getWriter().print(data);
		} catch (Exception ex) {
			String error = "{\"Result\":\"ERROR\",\"Message\":"
					+ ex.getMessage() + "}";
			response.getWriter().print(error);
			System.out.println("Json Result " + error);
			ex.printStackTrace();
		}		
	}
	
	/**
	 * Genera PDF acta volante de la mesa seleccionada
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void exportarActaVolante(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		
		//Objeto del service
		PdfBoxServiceMesaExamen service = new PdfBoxServiceMesaExamen();
		
		try {
			service.pdfA3a(request);
			String data = "{\"Result\":\"OK\"}";					
			response.getWriter().print(data);
		} catch (Exception ex) {
			String error = "{\"Result\":\"ERROR\",\"Message\":"
					+ ex.getMessage() + "}";
			response.getWriter().print(error);
			System.out.println("Json Result " + error);
			ex.printStackTrace();
		}
	}
	
	/**
	 * 
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void exportarActaDefinitiva(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		
		//Objeto del service
		PdfBoxServiceMesaExamen service = new PdfBoxServiceMesaExamen();
		
		try {
			service.pdfA3a(request);
			String data = "{\"Result\":\"OK\"}";					
			response.getWriter().print(data);
		} catch (Exception ex) {
			String error = "{\"Result\":\"ERROR\",\"Message\":"
					+ ex.getMessage() + "}";
			response.getWriter().print(error);
			System.out.println("Json Result " + error);
			ex.printStackTrace();
		}
	}	
}